import { View, Text, Image, RadioGroup, ScrollView, StickySection, StickyHeader, ListView, Snapshot } from "@tarojs/components";
import Taro, { useDidShow, useLoad } from "@tarojs/taro";
import { memo, useEffect, useState } from "react";
import { Empty, NavBar } from "@nutui/nutui-react-taro";
import useNavInfo from "../../../hooks/useNavInfo";
import { wxCode } from "../../../assets/files";
import { userCard, userRank, userTotal } from "../../../api/total";
import { ArrowLeft } from '@nutui/icons-react-taro'
import dayjs from "dayjs";
import { getParams, secondsToMinutes } from "../../../common/_";
import { getStore } from "../../../utils/localStore";
import { selectUserInfo } from "../../../api/user.js";
import "./index.scss";

const StudyTotalShare = () => {

  const [info, setInfo] = useState('')
  const [typeList, setTypeList] = useState([])

  useEffect(() => {
    console.log(getParams())
    setInfo(getParams())
    setTimeout(()=>{
      shere()
    },500)

  }, [])


  const shere = () => {
    Taro.createSelectorQuery().select("#target").node().exec(res => {
      console.log(res);
      const node = res[0].node
      node.takeSnapshot({
        type: 'arraybuffer',
        format: 'png',
        success: (ress) => {
          console.log(ress);
          const f = `${Taro.env.USER_DATA_PATH}/hello.png`
          const fs = Taro.getFileSystemManager();
          fs.writeFileSync(f, ress.data, 'binary')
          showShareImageMenu(f)
        },
        fail: (err) => {
          console.log(err);
        }
      })
    })
  }

  const showShareImageMenu = (path) => {
    if (Taro.showShareImageMenu) {
      Taro.showShareImageMenu({
        path: path,
        complete() {
          handleUpdate()
        },
      }).then().catch((err) => {
        console.log(err)
        const { errMsg } = err
        // 取消操作  errMsg === 'showShareImageMenu:fail cancel'
        // 拒绝授权  errMsg: "showShareImageMenu:fail auth deny"
        if (errMsg === 'showShareImageMenu:fail auth deny') {
          authorize({
            scope: 'writePhotosAlbum',
            showModal: true,
            authName: '保存图片到相册',
            success: () => {
              // this.downloadImg()
            },
          })
        }
      }).finally(() => {
        handleUpdate()
        // this.isDraw = false
      })
    } else {
      Taro.showToast({
        title: '小程序版本不支持该功能',
        icon: 'error',
      })
    }
  }

  const handleUpdate = () =>{
    Taro.navigateBack({
      delta:1
    })
  }

  useEffect(() => {
    if (info?.list?.length > 3) {
      console.log(info.list);
      setTypeList(info?.list.slice(0, 3))
    } else {
      setTypeList(info?.list)
    }
  }, [info])

  function _handleback() {
    Taro.navigateBack({
      delta: 1
    })
  }
  const { statusBarHeight } = useNavInfo();

  useEffect(() => {
    getUserInfo()
  }, [])
  
  const [userData, setUserData] = useState({})
  async function getUserInfo() {
    const { data } = await selectUserInfo({})
    setUserData(data)
  }

  return (
    <View className="mainWrap">
      <NavBar
        fixed
        style={{ backgroundColor: '#fff', left: 0, top: statusBarHeight }}
        back={
          <>
            <ArrowLeft color="#000000" />
          </>
        }
        onBackClick={(e) => _handleback()}
      >
        <span>分享</span>
      </NavBar>
      <View className="shareMainWrap" style={{ marginTop: 66 + statusBarHeight }}>
      <Snapshot id="target" className="snapshot">
        <View className="sharebgWrap">
         
            <View className="snapshotWrap" style={{paddingTop: statusBarHeight+74}}>
              <View className="infoWrap">
                <View className="topTit">
                  <Text className="shareTit">{dayjs().format("YYYY")}学习成就</Text>
                  <Text className="titDes">这是我们在一起的
                    <Text className="days"> {info?.days} </Text>
                    天，感谢你的一路陪伴</Text>
                </View>

                <View className="boxShare">
                <View className="shareContentWrap">
                  <Text className="contentText">这一年里，
                    <Text className="xutType">{userData?.userName}</Text>
                    学习了
                    <Text className="xutType">
                      {info?.videoWatchTotal}
                    </Text>
                    个视频，学习总时长
                    <Text className="xutType">
                      {secondsToMinutes(info?.videoWatchDuration)}
                    </Text>
                    ，参加了
                    <Text className="xutType">
                      {
                        typeList?.map((v, i) => {
                          return i === typeList.length - 1 ? v : v + '、'
                        })
                      }
                    </Text>
                    {typeList && '等类型的共'}
                    <Text className="xutType">
                      {info?.examTotal}
                    </Text>
                    次测试{typeList ? '，取得了优异的测试成绩。' : '。'}</Text>
                  <View className="cbot">
                    <Text className="contentText"><br />
                      {/* 我们共同见证了知识的力量在日常播种安全的种子， */}
                      我们共同见证了知识的力量在日常播种安全的种子，每一刻的学习都是对生命的尊重与守护，安全相伴，未来可期。</Text>
                  </View>

                </View>
                </View>

              </View>
              <View className="codeWrap">
                <Image className="wxCode" src={wxCode} />
                <Text className="xuexi">长按识别小程序码来一起学习吧</Text>
              </View>
            </View>
          
        </View>
        </Snapshot>
      </View>

    </View>
  );
}

export default StudyTotalShare;
